package com.znyj.cloud.thrift;

import com.znyj.cloud.thrift.lower.InnerThriftService;
import org.apache.log4j.Logger;
import org.apache.thrift.TProcessor;
import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.server.TNonblockingServer;
import org.apache.thrift.server.TServer;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TTransportException;

import javax.net.ssl.SSLException;
import java.security.cert.CertificateException;

/**
 * Created by gaoliwei02 on 17/8/9.
 */
//@Component
public class ThriftService implements Runnable {
    private static final Logger logger = Logger.getLogger(ThriftService.class);
    public static int PORT = 9976;

    public void init() throws CertificateException, SSLException, InterruptedException {
        try {

            String port = System.getProperty("http_port");
            if (port != null) {
                PORT = Integer.parseInt(port);
            }

            System.out.println("Thrift服务端开启.... 端口:" + PORT);
            TProcessor tprocessor = new InnerThriftService.Processor<InnerThriftService.Iface>(new InnerThriftServiceImpl());

            // 使用非阻塞式IO，服务端和客户端需要指定TFramedTransport数据传输的方式
            TNonblockingServerSocket serverTransport = new TNonblockingServerSocket(PORT);
            TNonblockingServer.Args tnbArgs = new TNonblockingServer.Args(serverTransport);

            tnbArgs.processorFactory(new TProcessorFactory(tprocessor));
            tnbArgs.transportFactory(new TFramedTransport.Factory());
            tnbArgs.protocolFactory(new TBinaryProtocol.Factory());

            TServer server = new TNonblockingServer(tnbArgs);
            server.setServerEventHandler(new MyTServerEventHandler());
            server.serve();


//            logger.error("新开一个thrift线程~~~~~~~~~~~~~~~~~~~~~~~~");
//            ThriftService thriftService = new ThriftService();
//            new Thread(thriftService).start();
//            logger.error("旧的thrift关闭线程~~~~~~~~~~~~~~~~~~~");
        } catch (TTransportException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            this.init();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (SSLException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
    }
}
